--[[
FilePath: \Lua\View\UIHeroManor\UIHeroManorMoveIn.lua
入驻列表
--]]

require 'View/UIBase/UIBase'

UIHeroManorMoveIn = UIBase.New(PanelNames.UIHeroManorMoveIn)
local _M = UIHeroManorMoveIn

_M.hasInit = false
_M.selectType = 0
_M.tableHeros = nil
_M.selectPartnerId = 0
_M.exchangePartnerId = 0
_M.ctrlHadBattleCtrl = nil
_M.selectList = nil
_M.isClick = false;
_M.isReplace = false;
_M.curManorPartnerId = 0
_M.manorModelId = 0
_M.selectModelId = 0
_M.isExchangeGuest = false

function _M.Init(cityId, index,type)
    _M.cityId = cityId or 1;
    _M.selectIndex = index or 1;
    _M.openType = type or 0;
    UIBase.Init(_M)
end

function _M:OnCreate()
    if not _M.hasInit then
        self.title = self:GetChild("title");
        self.txtTips = self:GetChild("tips");
        self.moveInManor = self:GetChild("MoveInManor");
        self.stateCtrl = self.moveInManor:GetController("state");
        self.heroMoveIn = self.moveInManor:GetChild("hero");
        self.listMoveInHouse = self:GetChild("listMoveInHouse");
        self:SetDynamicList(self.listMoveInHouse, self.ItemRender, nil, true);
        self.listAttr = self:GetChild("listAttr");
        self.typeCtrl = self:GetController("type");
        self.noCtrl = self:GetController("nothing");
        self.attrTips = self:GetChild("tips1");
        local heroList = self:GetChild("heroList");
        self:RegisterOnClick(heroList:GetChild("BackBtn"), self.OnBack);
        self.btnSure = heroList:GetChild("btnSure");
        self.itemGrid = heroList:GetChild("itemGrid");
        self.itemGrid.itemRenderer = self.listSelectHeroItem;
        self.itemGrid:SetVirtual();
        self.tab = {};
        for i = 0, 6 do
            table.insert(self.tab, heroList:GetChild("Tab"..i));
        end

        -- 替换门客提示
        self.tipsCtrl = self:GetController("tips");
        local exchangeHero = self:GetChild("exchangeHero");
        self.preHeroIcon = exchangeHero:GetChild("hero"):GetChild("icon");
        self.preHeroName = exchangeHero:GetChild("heroManorName");
        self.preHeadIcon = exchangeHero:GetChild("heroIcon1"):GetChild("head"):GetChild("HeadIcon");
        self.tagHeroIcon = exchangeHero:GetChild("hero2"):GetChild("icon");
        self.tagHeroName = exchangeHero:GetChild("heroManorName2");
        self.tagHeadIcon = exchangeHero:GetChild("heroIcon2"):GetChild("head"):GetChild("HeadIcon");
        self.moveInTips = exchangeHero:GetChild("tipText");
        self.btnCloseTipPanel = exchangeHero:GetChild("bgclose");
        self.btnConfirm = exchangeHero:GetChild("btnConfirm");
        self.btnCancel = exchangeHero:GetChild("btnCancel");

        _M.hasInit = true

        self:addEvent()
    end
end

function _M:addEvent()
    self.btnSure.onClick:Add(self.OnClickSure,self);
    for i = 1, #self.tab do
        self.tab[i].onClick:Add(function()
            _M:selectHeroType(i - 1);
        end);
    end
    self.btnCloseTipPanel.onClick:Add(function()
        self.tipsCtrl.selectedIndex = 0;
    end);
    self.btnCancel.onClick:Add(function()
        self.tipsCtrl.selectedIndex = 0;
    end);
    self.moveInManor.onClick:Add(function()
        if self.selectPartnerId > 0 then
            self.selectPartnerId = 0;
            self:RefreshHero();
            self.itemGrid:RefreshVirtualList();
        end
    end);
    self:RegisterEvent(Config.EventType.FreshManorInfo,self.FreshManorInfo);
end

function _M:removeEvent()
    self.btnSure.onClick:Remove(self.OnClickSure);
    for i = 1, #self.tab do
        self.tab[i].onClick:Clear();
    end
    self.btnCloseTipPanel.onClick:Clear();
    self.btnCancel.onClick:Clear();
    self.moveInManor.onClick:Clear();
end

function _M:OnClickSure()
    if self.openType == 0 then
        if self.selectPartnerId == 0 then
            UISysTips.AddMsg(getLanguage("HeroManorText16"));
            return;
        end
        if self.isClick then
            return;
        end
        if tonumber(self.curManorPartnerId) == self.selectPartnerId then
            self:OnBack();
            return;
        end
        local list = {};
        table.insert(list, self.selectPartnerId);
        if self.guests ~= nil then
            for i = 1, #self.guests do
                if i > self.selectHeroNum then
                    break;
                else
                    local id = tonumber(self.guests[i]);
                    if self.selectPartnerId ~= id and id > 0 then
                        table.insert(list, id);
                    end
                end
            end
        end
        if logicMgr.HeroManorManager.isManorGuest(self.selectPartnerId) then
            local pop = CtrlManager.GetCtrl(PanelNames.UICommonPop)
            pop.Init(137, function (flag)
                if flag then
                    self.isClick = true;
                    HeroManorHandler.sendReqManorInviteMessage(self.cityId, self.selectIndex, list);
                end
            end)
        else
            self.isClick = true;
            HeroManorHandler.sendReqManorInviteMessage(self.cityId, self.selectIndex, list);
        end
    else
        if self.isClick then
            return;
        end
        self.isClick = true;
        local list = {};
        table.insert(list, self.selectPartnerId);
        for k, v in pairs(self.guests) do
            if tonumber(v) > 0 then
                table.insert(list, tonumber(v));
            end
        end
        HeroManorHandler.sendReqManorInviteMessage(self.cityId, self.selectIndex, list);
    end
end

function _M:selectHeroType(index)
    if self.selectType == index then
        return;
    end
    self.selectType = index;
    self:updateSelectHeroItem();
end

function _M:updateSelectHeroItem()
    if self.tableHeros == nil then
        self.tableHeros = logicMgr.HeroManager.getOwnerHeroList();
        table.sort(self.tableHeros, logicMgr.HeroManager.sortHeroWithQuality);
    end
    self.typeHeros = {};
    for i = 1, #self.tableHeros do
        if self.selectType == 0 or self.tableHeros[i].type == self.selectType then
            if not logicMgr.HeroManorManager.isManorMaster(self.tableHeros[i].partnerId) then
                if self.openType == 0 then
                    if self.tableHeros[i].star >= self.heroStar then
                        table.insert(self.typeHeros, self.tableHeros[i]);
                    end
                else
                    table.insert(self.typeHeros, self.tableHeros[i]);
                end
            else
                if self.curManorPartnerId == self.tableHeros[i].partnerId and self.openType == 0 then
                    table.insert(self.typeHeros, self.tableHeros[i]);
                end
            end
        end
    end
    self.ctrlHadBattleCtrl = nil;
    self.itemGrid.numItems = #self.typeHeros;
end

function _M.listSelectHeroItem(index, itemObj)
    local hero = _M.typeHeros[index + 1];
    local ctrlHadBattle = itemObj:GetController("ctrlHadBattle")
    local charactor = CtrlManager.GetCtrl(PanelNames.HeadRectItem);
    if charactor ~= nil and hero ~= nil then
        charactor.initData(itemObj, hero);
        if logicMgr.HeroManorManager.isManorGuest(hero.partnerId) and not logicMgr.HeroManorManager.isGuestByManor(_M.selectPartnerId, hero.partnerId) then
            charactor.showManor(itemObj, hero.partnerId);
        end
    end
    itemObj.onClick:Clear();
    ctrlHadBattle.selectedIndex = 0;
    if _M.openType == 0 then
        if tonumber(hero.partnerId) == _M.selectPartnerId then
            ctrlHadBattle.selectedIndex = 1;
            _M.ctrlHadBattleCtrl = ctrlHadBattle;
        end
        itemObj.onClick:Add(function()
            if _M.ctrlHadBattleCtrl ~= nil then
                _M.ctrlHadBattleCtrl.selectedIndex = 0;
                _M.ctrlHadBattleCtrl = nil;
            end
            if tonumber(hero.partnerId) == _M.selectPartnerId then
                _M.selectPartnerId = 0;
                _M:RefreshHero();
            else
                if hero.star >= _M.heroStar then
                    _M.selectPartnerId = tonumber(hero.partnerId);
                    ctrlHadBattle.selectedIndex = 1;
                    _M.ctrlHadBattleCtrl = ctrlHadBattle;
                    _M:RefreshHero(hero);
                else
                    UISysTips.AddMsg(getLanguage("HeroManorText07"));
                end
            end
        end);
    else
        local isSelect = _M:isSelect(hero.partnerId);
        if isSelect then
            ctrlHadBattle.selectedIndex = 1;
        else
            ctrlHadBattle.selectedIndex = 0;
        end
        itemObj.onClick:Add(function()
            if isSelect then
                isSelect = false;
                ctrlHadBattle.selectedIndex = 0;
                if _M.selectNum > 0 then
                    _M:removeHero(hero.partnerId);
                    _M.selectNum = _M.selectNum - 1;
                end
            else
                if _M.selectNum >= _M.selectHeroNum then
                    UISysTips.AddMsg(getLanguage("HeroManorText15"));
                else
                    if logicMgr.HeroManorManager.isManorGuest(hero.partnerId) and not logicMgr.HeroManorManager.isGuestByManor(_M.selectPartnerId, hero.partnerId) then
                        _M.tipsCtrl.selectedIndex = 1;
                        _M:showTips(logicMgr.HeroManorManager.getManorMasterByGuest(hero.partnerId), hero, function()
                            _M.tipsCtrl.selectedIndex = 0;
                            isSelect = true;
                            _M.selectNum = _M.selectNum + 1;
                            ctrlHadBattle.selectedIndex = 1;
                            _M:selectHero(hero.partnerId);
                            _M.isExchangeGuest = true;
                            _M:OnClickSure();
                        end)
                    else
                        isSelect = true;
                        _M.selectNum = _M.selectNum + 1;
                        ctrlHadBattle.selectedIndex = 1;
                        _M:selectHero(hero.partnerId);
                    end
                end
            end
        end);
    end
end

-- 显示
function _M:OnEnable()
    self.typeCtrl.selectedIndex = self.openType;
    self.ctrlItem = CtrlManager.GetCtrl(PanelNames.HeadRectBItem);
    self.heroNum = 0;
    self.selectHeroNum = 0;
    self.isReplace = false;

    self.heroManorModel = dataTable.getDataTable("t_heromanormodel");
    for k, v in pairs(self.heroManorModel) do
        self.heroNum = self.heroNum + 1;
    end
    self.title.text = getLanguage("HeroManorText09");
    if self.openType == 0 then
        self.txtTips.text = getLanguage("HeroManorText07");
    else
        self.txtTips.text = getLanguage("HeroManorText10");
    end
    self:RefreshView();
end

function _M:FreshManorInfo()
    if self.openType == 0 then
        --self:OnBack();
        --if self.isReplace then
        --    showUI(PanelNames.UIHeroManor, self.cityId, self.selectIndex);
        --end
        self:setHeroManorMasterTA();
        showUI(PanelNames.UIHeroManorMoveInSuccess, self.cityId, self.selectIndex);
        --return;
    else
        self:setHeroManorGuestTA();
        logicMgr.HeroManager.updateHeroBaseAttr(self.selectPartnerId,true);
    end
    FireEvent(Config.EventType.ReFreshHeroPower);
    if self.isExchangeGuest then
        self.isExchangeGuest = false;
        self.isClick = false;
        self.selectPartnerId = 0;
        if self.exchangePartnerId > 0 then
            logicMgr.HeroManager.updateHeroBaseAttr(self.exchangePartnerId,false);
            self.exchangePartnerId = 0;
        end
        self:RefreshView();
    else
        self:OnBack();
    end
    --self.isClick = false;
    --self.selectPartnerId = 0;
    --self:RefreshView();
end

function _M:setHeroManorMasterTA()
    local setFormation = {}
    setFormation["manor_id"] = self.selectIndex;
    if self.isReplace then
        setFormation["exchange_manor_hero"] = self.selectModelId;
        TAManager.TrackByDictionary("exchange_manor", setFormation);
    else
        setFormation["first_manor_hero"] = self.selectModelId;
        TAManager.TrackByDictionary("first_manor", setFormation);
    end
end

function _M:setHeroManorGuestTA()
    local setFormation = {}
    setFormation["manor_id"] = self.selectIndex;
    setFormation["main_hero"] = self.manorModelId;
    local index = 1;
    for k, v in pairs(self.guests) do
        if tonumber(v) > 0 then
            local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(v, true);
            setFormation["guest"..index] = heroInfo["partnerModelId"];
            index = index + 1;
        end
    end
    TAManager.TrackByDictionary("manor_guest", setFormation);
end

function _M:RefreshView()
    local manorInfo = logicMgr.HeroManorManager.getManorInfo(self.cityId, self.selectIndex);
    if self.openType == 0 then
        local modelData = logicMgr.HeroManorManager.getCityModelData(self.selectIndex);
        if modelData ~= nil then
            self.heroStar = modelData.f_HeroQualityLimit;
        else
            self.heroStar = 100;
        end
        if manorInfo.masterId == nil or tonumber(manorInfo.masterId) == 0 then
            self:RefreshHero();
        else
            self.isReplace = true;
            self.curManorPartnerId = manorInfo.masterId;
            self.selectPartnerId = tonumber(manorInfo.masterId);
            local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(manorInfo.masterId, true);
            self.guests = logicMgr.HeroManorManager.getManorVisitors(manorInfo.masterId) or {};
            self:RefreshHero(heroInfo);
        end
    else
        self.selectPartnerId = tonumber(manorInfo.masterId);
        local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(manorInfo.masterId, true);
        self.manorModelId = heroInfo["partnerModelId"] or heroInfo["f_HeroID"] or 0;
        self.heroStar = heroInfo.star;
        local visitors = logicMgr.HeroManorManager.getManorVisitors(manorInfo.masterId) or {};
        self.guests = {};
        self.selectNum = 0;
        for i = 1, self.heroNum do
            if visitors[i] == nil then
                self.guests[i] = "0";
            else
                self.guests[i] = visitors[i];
                self.selectNum = self.selectNum + 1;
            end
        end
        self.selectHeroNum = 0;
        self:RefreshAttr();
        self.listMoveInHouse.numItems = self.heroNum;
    end
    self:updateSelectHeroItem();
end

function _M:RefreshHero(heroInfo)
    if heroInfo == nil then
        self.stateCtrl.selectedIndex = 1;
        self.selectModelId = 0;
    else
        self.stateCtrl.selectedIndex = 2;
        self.selectModelId = heroInfo.partnerModelId;
        self.ctrlItem.initData(self.heroMoveIn, heroInfo);
        self.ctrlItem.ShowOwnCount(self.heroMoveIn, false);
        self.selectHeroNum = 0;
        for k, v in pairs(self.heroManorModel) do
            if heroInfo.star >= v.f_MasterQuality then
                self.selectHeroNum = self.selectHeroNum + 1;
            end
        end
    end
end


function _M:selectHero(partnerId)
    --table.insert(self.guests, tostring(partnerId));
    for i = 1, self.heroNum do
        if self.guests[i] == "0" then
            self.guests[i] = tostring(partnerId);
            break;
        end
    end
    self.selectHeroNum = 0;
    self:RefreshAttr();
    self.listMoveInHouse.numItems = self.heroNum;
end

function _M:removeHero(partnerId)
    for i = 1, self.heroNum do
        if self.guests[i] == tostring(partnerId) then
            self.guests[i] = "0";
            break;
        end
    end
    self.selectHeroNum = 0;
    self:RefreshAttr();
    self.listMoveInHouse.numItems = self.heroNum;
end

function _M:isSelect(partnerId)
    for k, v in pairs(self.guests) do
        if v == tostring(partnerId) then
            return true;
        end
    end
    return false;
end

function _M:ItemRender(index, go)
    local state = go:GetController("state");
    local hero = go:GetChild("hero");
    local unlockTips = go:GetChild("unlockTips");
    go.onClick:Clear();
    local cfg = self.heroManorModel[tostring(index)];
    if self.heroStar < cfg.f_MasterQuality then
        state.selectedIndex = 0;
        unlockTips.text = string.format(getLanguage("HeroManorText11"), EnumConst.StarType[cfg.f_MasterQuality / 10]);
    else
        self.selectHeroNum =  self.selectHeroNum + 1;
        if self.guests[index] == nil or self.guests[index] == "0" then
            state.selectedIndex = 1;
        else
            state.selectedIndex = 2;
            local heroInfo = logicMgr.HeroManager.getHeroDatabyPartnerId(self.guests[index], true);
            local item = CtrlManager.GetCtrl(PanelNames.HeadRectBItem);
            item.initData(hero, heroInfo);
            item.ShowOwnCount(hero, false);
            go.onClick:Add(function()
                if self.selectNum > 0 then
                    self:removeHero(heroInfo.partnerId);
                    self.selectNum = self.selectNum - 1;
                    self.itemGrid:RefreshVirtualList();
                end
            end);
        end
    end
end

function _M:RefreshAttr()
    self.listAttr:RemoveChildrenToPool();
    local attrItems = logicMgr.HeroManorManager.getAllAttrByGuest(self.guests, self.selectPartnerId);
    self.noCtrl.selectedIndex = 0;
    if attrItems == nil or table.nums(attrItems) < 1 then
        self.noCtrl.selectedIndex = 1;
        local starCfg = logicMgr.HeroManorManager.getHeroManorData(self.manorModelId, 20, true);
        if starCfg == nil then
            self.attrTips.text = "";
        else
            self.attrTips.text = string.format(getLanguage("HeroManorText20"), EnumConst.StarType[starCfg[1].f_HeroStar / 10]);
        end
    else
        for k, v in pairs(attrItems) do
            local item = self.listAttr:AddItemFromPool();
            logicMgr.HeroManorManager.setAttrItemInfo(item, k, v);
        end
    end
end

function _M:showTips(partnerId, heroInfo, func)
    self.btnConfirm.onClick:Clear();
    local preName = "";
    local tagName = "";
    local heroData = logicMgr.HeroManager.getHeroDatabyPartnerId(partnerId, true);
    if heroData ~= nil then
        self.exchangePartnerId = tonumber(partnerId);
        local heroModelId = heroData["partnerModelId"] or heroData["f_HeroID"] or 0;
        local heroUseSkinId = logicMgr.SkinManager.getHeroSkinId(heroModelId)
        if heroUseSkinId and tonumber(heroUseSkinId) > 0 then
            self.preHeroIcon.url = "ui://HalfBodyAtlas/" ..logicMgr.SkinManager.GetHeroBIconBySkinId(heroUseSkinId);
        else
            self.preHeroIcon.url = "ui://HalfBodyAtlas/" .. heroData["halfIcon"];
        end
        preName = heroData.name;
        self.preHeroName.text = string.format(getLanguage("HeroManorText06"), heroData.name);
    end
    heroData = logicMgr.HeroManager.getHeroDatabyPartnerId(self.selectPartnerId, true);
    if heroData ~= nil then
        local heroModelId = heroData["partnerModelId"] or heroData["f_HeroID"] or 0;
        local heroUseSkinId = logicMgr.SkinManager.getHeroSkinId(heroModelId)
        if heroUseSkinId and tonumber(heroUseSkinId) > 0 then
            self.tagHeroIcon.url = "ui://HalfBodyAtlas/" ..logicMgr.SkinManager.GetHeroBIconBySkinId(heroUseSkinId);
        else
            self.tagHeroIcon.url = "ui://HalfBodyAtlas/" .. heroData["halfIcon"];
        end
        tagName = heroData.name;
        self.tagHeroName.text = string.format(getLanguage("HeroManorText06"), heroData.name);
    end
    local modelId = heroInfo["partnerModelId"] or heroInfo["f_HeroID"] or 0;
    logicMgr.HeroManorManager.setHeadIcon(self.preHeadIcon, modelId, heroData.icon);
    logicMgr.HeroManorManager.setHeadIcon(self.tagHeadIcon, modelId, heroData.icon);
    self.moveInTips.text = string.format(getLanguage("HeroManorText17"), preName, heroInfo.name, tagName);
    self.btnConfirm.onClick:Add(function()
        if func ~= nil then
            func();
        end
    end);
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();
    self.hasInit = false;
    self.selectType = 0;
    self.tableHeros = nil;
    self.selectPartnerId = 0;
    self.ctrlHadBattleCtrl = nil;
    self.selectList = nil;
    self.isClick = false;
    self.curManorPartnerId = 0;
    self.manorModelId = 0;
    self.selectModelId = 0;
    self.isExchangeGuest = false;
    self.exchangePartnerId = 0;
end

return _M;